package com.henghe.frame.core.filter;

import com.henghe.frame.common.entity.InputStreamHttpServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/28 14:17
 */
public class RequestFilter implements Filter {


    private List<Pattern> patterns = new ArrayList();

    @Override
    public void init(FilterConfig config) {
        String excludePath = config.getInitParameter("excludePath");
        if (StringUtils.isNotEmpty(excludePath)) {
            String[] filters = excludePath.split(",");
            String[] var3 = filters;
            int var4 = filters.length;

            for (int var5 = 0; var5 < var4; ++var5) {
                String filter = var3[var5];
                patterns.add(Pattern.compile(filter));
            }
        }
        patterns.add(Pattern.compile("v2/api-docs.*"));
        patterns.add(Pattern.compile("configuration/ui.*"));
        patterns.add(Pattern.compile("swagger-resources.*"));
        patterns.add(Pattern.compile("configuration/security.*"));
        patterns.add(Pattern.compile("swagger-ui.html"));
        patterns.add(Pattern.compile("spec"));
        patterns.add(Pattern.compile("healthy"));
        patterns.add(Pattern.compile("webjars.*"));
        patterns.add(Pattern.compile("error"));
        patterns.add(Pattern.compile("druid/*.*"));
        patterns.add(Pattern.compile("doc.html"));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String url = servletRequest.getRequestURI().substring(servletRequest.getContextPath().length());
        if (url.startsWith("/") && url.length() > 1) {
            url = url.substring(1);
        }
        /**
         * 忽略的路径直接过滤掉
         */
        if (isInclude(url)) {
            chain.doFilter(servletRequest, response);
            return;
        }

        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            requestWrapper = new InputStreamHttpServletRequestWrapper(servletRequest);
            chain.doFilter(requestWrapper, response);
        }
    }

    private boolean isInclude(String url) {
        Iterator var2 = patterns.iterator();
        Matcher matcher;
        do {
            if (!var2.hasNext()) {
                return false;
            }
            Pattern pattern = (Pattern) var2.next();
            matcher = pattern.matcher(url);
        } while (!matcher.matches());
        return true;
    }
}
